package com.chinasofti.zbest.web;

import com.alipay.api.AlipayApiException;
import com.chinasofti.zbest.dao.model.*;
import com.chinasofti.zbest.service.*;
import com.chinasofti.zbest.service.info.ProductCartInfo;
import com.chinasofti.zbest.web.form.OrderForm;
import com.chinasofti.zbest.web.form.OrderTMForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author zbest
 * @since 2019-05-28
 */
@Controller
@Slf4j
public class OrderController extends BaseController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IUserAddrService userAddrService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IOrderTMService orderTMService;

    @Autowired
    private IShopCartService shopCartService;

    /**
     * 生成订单
     *
     * @return
     */
    @RequestMapping("createOrder")
    public String torder(ModelMap modelMap , HttpSession session , OrderForm orderForm , String categoryName) {
        User user = (User) session.getAttribute("user");
        log.info(user.getUsername() + "的订单页面");
        Product product = (Product) session.getAttribute("product");
        if (orderForm.getProductCount() == null) { orderForm.setProductCount(1); }

        orderForm.setProductId(product.getProductId());
        orderForm.setCategoryName(categoryName);
        orderForm.setUserId(user.getUserId());
        orderForm.setUsername(user.getUsername());
        orderForm.setProductPrice(product.getProductPrice());
        orderForm.setProductPicture(product.getProductPicture());

        Zborder zborder = orderService.createOrder(session , orderForm );
        List<UserAddr> userAddr = userAddrService.queryAllByAddrId(user.getUserId());
        Integer proCount = product.getProductRepertory() - orderForm.getProductCount();
        Integer proSales = orderForm.getProductCount();
        productService.midifyProCount(product.getProductId() , proCount,proSales);

        modelMap.addAttribute("zborder" , zborder);
        modelMap.addAttribute("userAddr" , userAddr);

        log.info("进入oder页面");
        return "order/order";
    }


//    @RequestMapping(value ="closeAccount",method = RequestMethod.POST)
//    @ResponseBody
//    public Map<String,Long> torder(@RequestBody List<ShopCart> shoppingCart, HttpSession session) {
//        long number=new Date().getTime();
//        Map<String,Long> result=new HashMap<>();
//        session.setAttribute(""+number,shoppingCart);
//        result.put("result",number);
//        return result;
//    }


    //购物车过来生成订单
    @RequestMapping("shopCartCreatOrder")
    public String shopCartCreatOrder(String cartId, ModelMap modelMap,HttpSession session,OrderForm orderForm ){
        Integer shopCartId = Integer.valueOf(cartId);

        ShopCart shopCart = shopCartService.queryByCartId(shopCartId);
        log.info(shopCart.toString());

        User user = (User) session.getAttribute("user");
        log.info(user.getUsername() + "的订单页面");

        Product product = productService.queryByProductNum(shopCart.getProductNumber());
        shopCartService.del(user.getUserId(),product.getProductNumber());

        orderForm.setProductCount(shopCart.getProductCount());
        orderForm.setProductId(product.getProductId());
        orderForm.setCategoryName(shopCart.getCategoryName());
        orderForm.setUserId(user.getUserId());
        orderForm.setUsername(user.getUsername());
        orderForm.setProductPrice(product.getProductPrice());
        orderForm.setProductPicture(product.getProductPicture());

        Zborder zborder = orderService.createOrder(session , orderForm );
        List<UserAddr> userAddr = userAddrService.queryAllByAddrId(user.getUserId());
        Integer proCount = product.getProductRepertory() - orderForm.getProductCount();
        Integer proSales = orderForm.getProductCount();
        productService.midifyProCount(product.getProductId() , proCount,proSales);

        modelMap.addAttribute("zborder" , zborder);
        modelMap.addAttribute("userAddr" , userAddr);

        return "order/order";
    }

    /**
     * 支付成功跳成功页面
     */
    @RequestMapping("tok")
    public String tok(HttpSession session,ModelMap modelMap,OrderTMForm orderTMForm,HttpServletResponse response, HttpServletRequest request)
            throws IOException, AlipayApiException{

        User user = (User) session.getAttribute("user");
        UserAddr userAddr = userAddrService.queryOneUserAddrUn(user.getUserId());

        if (userAddr == null) {
            modelMap.addAttribute("userAddrMsg" , "您的收货地址为空");
            return "user/address";
        } else {
            orderTMForm.setAddress(userAddr.getAddress());
            orderTMForm.setReceivingName(userAddr.getReceivingName());
            orderTMForm.setReceivingPhone(userAddr.getReceivingPhone());
            orderTMForm.setUserId(user.getUserId());
            log.info(orderTMForm.toString());

            orderTMService.createOrderTM(orderTMForm);
            /**
             * 支付成功操作
             */
            orderService.modifyStatus("waitShipped",orderTMForm.getOrderNum());

            log.info("进入ok页面");
            return "order/ok";
        }
    }



    /**
     * 返回myorderq页面
     */
    @RequestMapping("toMyorderq")
    public String toMyorderq(HttpSession session , ModelMap modelMap,OrderTMForm orderTMForm) {

        User user = (User) session.getAttribute("user");
        List<Zborder> orderList = orderService.queryAllOrderById(user.getUserId());
        modelMap.addAttribute("orderList",orderList);


        log.info("进入myorderq页面,orderList为"+orderList);
        return "order/myorderq";
    }


    /**
     * 订单详情
     */
    @RequestMapping("toOrderxq")
    public String toOrderxq(HttpSession session,String orderNum,ModelMap modelMap){

        User user =(User)session.getAttribute("user");

        Zborder order = orderService.queryByOrderNum(user.getUserId() , orderNum);
        OrderTM orderTM = orderTMService.queryByOrderNum(user.getUserId() , orderNum);

        log.info("queryByOrderNum：order("+order+")");
        log.info("queryByOrderNum：orderTM("+orderTM+")");
        modelMap.addAttribute("order",order);
        modelMap.addAttribute("orderTM",orderTM);
        return "order/orderxq";
    }

    /**
     * 查询订单
     */
    @RequestMapping("searchOrder")
    private String searchOrder(HttpSession session ,String status,ModelMap modelMap){

        log.info("status:"+status);
        User user = (User)session.getAttribute("user");
        List<Zborder> orderList = orderService.queryByStatus(user.getUserId() , status);

        StringBuilder jsonSb = new StringBuilder();
        jsonSb.append("{\"success\":true").append(",\"data\":[");
        for(Zborder o :orderList) {
            jsonSb.append("\"").append(o).append("\",");
        }
        jsonSb.deleteCharAt(jsonSb.length()-1);
        jsonSb.append("]}");

        log.info(jsonSb.toString());

//        modelMap.addAttribute("orderList",jsonSb);
        return "order/myorderq";

    }

    @RequestMapping("modifyOrderByOrderStatus")
    public String modifyOrderByOrderStatus(HttpSession session,String orderNum,ModelMap modelMap){

        String status="waitEvaluated";

        log.info("status:"+status+",orderNum"+orderNum);
        orderService.modifyOrderByOrderStatus(orderNum,status);
        User user = (User) session.getAttribute("user");
        List<Zborder> orderList = orderService.queryAllOrderById(user.getUserId());
        modelMap.addAttribute("orderList",orderList);


        log.info("进入myorderq页面,orderList为"+orderList);
        return "order/myorderq";
    }

    //确认收货
//    @RequestMapping("toWaitReceiving")
//    public String toWaitReceiving(String status,String orderNum,HttpSession session,ModelMap modelMap){
//        log.info("status:"+status+"orderNum:"+orderNum);
//        orderService.modifyStatus(status,orderNum);
//        User user = (User) session.getAttribute("user");
//        List<Zborder> orderList = orderService.queryAllOrderById(user.getUserId());
//        modelMap.addAttribute("orderList",orderList);
//
//
//        log.info("进入myorderq页面,orderList为"+orderList);
//        return "order/myorderq";
//    }

    @RequestMapping("alipay")
    public String toAlipay(HttpSession session,ModelMap modelMap,OrderTMForm orderTMForm,HttpServletResponse response, HttpServletRequest request)
            throws IOException, AlipayApiException{
        /**
         * 支付操作
         */
        orderService.ali(response,request,orderTMForm.getOrderNum(),orderTMForm.getOrderPay());

        return "order/alipay";
    }



}

